// --信息填报页面--
var app = getApp();
var util = require('../../../utils/util.js');
var sex, address, lxbx, input_id, sfwc, fromwhere, lxbx04zhengzhuang, flag = "1",   zhengzhuang,  lxbx04qtxx,mz_memo;
var workaddress, workphone, startwhere, crosswhere, traininfo, train_memo; // 下面火车 站信息用
Page({

  /**
   * 页面的初始数据
   */ 

  data: {
    btnEn: false,
    twocode_en: true,
    modalHidden: true,//是否隐藏对话框
    // modalHidden1: true,//是否隐藏对话框
    modatext: "请注意：体温情况异常,请确认与实际情况相符！",
  },
  test: function (e) {

    // console.log("用户信息", e)


  },
  onLoad: function () {
    this.findOpenid();
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../../chooseLib/chooseLib',
      })
      return
    }
  },

  //拍照或者从相册选择要识别的照片
  photo(type) {
    let that = this

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], ///'original',压缩图
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        let imgUrl = res.tempFilePaths[0];
        // console.log("photo", imgUrl)
        that.uploadImg(app.globalData.openid + new Date().getTime(), imgUrl)
      }
    })
  },

  // 上传图片到云存储
  uploadImg(type, imgUrl) {
    let that = this
    wx.cloud.uploadFile({
      cloudPath: 'ocr/' + type + '.png',
      filePath: imgUrl, // 文件路径
      success: res => {
        // console.log("上传成功", res.fileID)
        that.getImgUrl(type, res.fileID)
      },
      fail: err => {
        // console.log("上传失败", err)
      }
    })
  },

  //获取云存储里的图片url
  getImgUrl(type, imgUrl) {
    wx.showToast({
      title: '正在识别',
      icon: 'loading'
    })
    let that = this
    wx.cloud.getTempFileURL({
      fileList: [imgUrl],
      success: res => {
        let imgUrl = res.fileList[0].tempFileURL
        // console.log("获取图片url成功", imgUrl)
        that.shibie(type, imgUrl)
      },
      fail: err => {
        // console.log("获取图片url失败", err)
      }
    })
  },

  //调用云函数，实现OCR识别
  shibie(type, imgUrl) {
    // console.log("识别成功shibie", type)
    let that = this
    wx.cloud.callFunction({
      name: "photo",
      data: {
        type: "shenfenzheng",
        imgUrl: imgUrl
      },
      success(res) {
        // console.log("识别成功", res)
        that.setData({
          name: res.result.name,
          sfz: res.result.id
        })
      },
      fail(res) {
        // console.log("识别失败", res)
      }
    })
    // console.log("识别成功res.result.name")


  }
,
  twocode_en_false: function () {
    // console.log("修改")
    this.setData({
      twocode_en: true,
      btnEn: false,
    })
  },
  createTwoCode: function () {
    wx.redirectTo({
      url: '/pages/createTwoCode/createTwoCode'
    })
  },
  getPhoneNumber(e) {
    var that = this;
    wx.cloud.callFunction({
      name: 'getPhone',
      data: {
        weRunData: wx.cloud.CloudID(e.detail.cloudID),      
      }
    }).then(res => {
      this.setData({
        phone: res.result,
        twocode_en: true,
        btnEn: false,
      })
    }).catch(err => {
    });
  },
  //事件处理函数
  // bindViewTap: function () {
  //   this.setData({
  //     modalHidden: !this.data.modalHidden,

  //   })
  // },
  //确定按钮点击事件
  modalBindaconfirm: function () {
    this.setData({
      modalHidden: !this.data.modalHidden,
    })

  },
  //取消按钮点击事件
  // modalBindcancel: function () {
  //   this.setData({
  //     modalHidden: !this.data.modalHidden,
  //   })
  // },

  findOpenid: function () {
    const db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'login',
      complete: res => {
        app.globalData.openid = res.result.openid
        db.collection('base_zmyy').where({
          _openid: app.globalData.openid
        }).limit(1)
          .orderBy('addtime', 'desc')//按字段排序
          .get()
          .then(res => {


            if (res.data.length) {
              // console.log('查询数据库，data:', res.data)
              // console.log('查询数据库，data:', res.data[0])
              
              this.setData({
                name: res.data[0].name,
                // sex: res.data[0].sex,
                sfz: res.data[0].sfz,
                // address: res.data[0].address,
                phone: res.data[0].phone,               
                memo: res.data[0].zy_memo,
                laifangmudi: res.data[0].laifangmudi,
                beifangzhekeshi: res.data[0].beifangzhekeshi,
                beifangzhename: res.data[0].beifangzhename,
              })
              mz_memo = res.data[0].mz_memo
              address= res.data[0].address,
            sex= res.data[0].sex,
            lxbx= res.data[0].lxbx,
            sfwc= res.data[0].sfwc,
              fromwhere = res.data[0].fromwhere,
            lxbx04zhengzhuang= res.data[0].lxbx04zhengzhuang,
            zhengzhuang= res.data[0].zhengzhuang,  
            lxbx04qtxx= res.data[0].lxbx04qtxx,
                input_id = res.data[0]._id,
                // 下面火车 站信息用
                workaddress = res.data[0].workaddress,
                workphone = res.data[0].workphone,
                startwhere = res.data[0].startwhere,
                crosswhere = res.data[0].crosswhere,
                traininfo = res.data[0].traininfo,
                train_memo = res.data[0].train_memo,
              flag = parseInt(res.data[0].flag) + 1 ///标记是否第一次填写
              if (res.data[0].name && res.data[0].sfz && res.data[0].laifangmudi && res.data[0].beifangzhekeshi && res.data[0].phone
                && res.data[0].beifangzhename) {
                app.globalData.input_id = "2" + app.globalData.openid
                // console.log('信息完整')
                this.setData({
                  twocode_en: false,
                  btnEn: true,
                })
                      if (parseInt(flag) == 2) {
                        // console.log('第二次添加', flag)
                        db.collection('base_zmyy').doc(res.data[0]._id).update({
                          data: {
                            flag: "2",
                          }
                        })
                      }
                      else {
                        // console.log('不添加', flag)
                      }
              }
            }
            else {
              // console.log('没查询到数据', res.data)
            }
          })

      }
    })


  },
 

  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)

    this.setData({ btnEn: true, twocode_en: false, })
    if (
      e.detail.value.name_mz && e.detail.value.sfzh && 
      e.detail.value.laifangmudi && e.detail.value.beifangzhekeshi && e.detail.value.beifangzhename) {
      if (e.detail.value.phone) {
        const db = wx.cloud.database()
        try {
        db.collection('base_zmyy').doc(input_id).remove({
          success: function (res) {
            // console.log('删除成功', input_id)
          }
        })
        } catch { }
        db.collection('base_zmyy').add({
          data: {
            name: e.detail.value.name_mz,
            sfz: e.detail.value.sfzh,
            phone: e.detail.value.phone,
            laifangmudi: e.detail.value.laifangmudi,
            beifangzhekeshi: e.detail.value.beifangzhekeshi,
            beifangzhename: e.detail.value.beifangzhename,
            zy_memo: e.detail.value.memo,
            addtime: util.formatTime(new Date()),
            // 保存　门诊信息
            mz_memo: mz_memo,
            sex: sex,
            address: address,
            // lxbx: arrlxbxv,
            lxbx: lxbx,
            sfwc: sfwc,
            fromwhere: fromwhere,
            lxbx04zhengzhuang: lxbx04zhengzhuang,
            zhengzhuang: zhengzhuang,
            lxbx04qtxx: lxbx04qtxx,
            // 下面住院信息用
            outtime: "", 
            flag: flag,
            // 下面火车 站信息用
            workaddress: workaddress,
            workphone: workphone,
            startwhere: startwhere,
            crosswhere: crosswhere,
            traininfo: traininfo,
            train_memo: train_memo,
          }
          ,
          success: res => {
            // 在返回结果中会包含新创建的记录的 _id                  
            // wx.showToast({
            //   title: '新增记录成功',
            // })

            // console.log('添加数据02', res._id)
            app.globalData.input_id = "2" + app.globalData.openid
            // app.globalData.input_link="station"
            wx.redirectTo({
              url: '/pages/createTwoCode/createTwoCode'
            })
            this.setData({ btnEn: false, twocode_en: true, })
          },
          fail: err => {
            wx.showToast({
              icon: 'none',
              title: '新增记录失败,请找当值人员手工登记！'
            })
            // console.error('[数据库] [新增记录] 失败：', err)
          }
        })

      }
      else {
        // console.log('请更改地址信息：', e.detail.value)
        wx.showToast({
          icon: 'loading',
          title: '请获取手机号',
        })
        this.setData({ btnEn: false, twocode_en: true, })
      }
    }
    else {
      // console.log('form发生了submit事件，携带数据为：', e.detail.value)
      wx.showToast({
        icon: 'loading',
        title: '请填全红字信息',
      })
      this.setData({ btnEn: false, twocode_en: true, })
    }
    // this.setData({ btnEn: false })
  },
 


})